var express = require('express');
const fs = require('fs');
var router = express.Router();
let cookie = require("cookie-parser");
var persons = fs.readFileSync("D:/Offcn/EP3/day10/xiaou/persons.json")
persons = JSON.parse(persons)
router.use(cookie())

router.get("/login", (req, res) => {
    //res.send("登录")
    res.render("pages/loginAndRegister/login.html")
})

router.post("/login", (req, res) => {
    if ((req.cookies.code).toUpperCase()==(req.body.code).toUpperCase()) {
        persons.find(v => v.username == req.body.username && v.password == req.body.password)?res.send("登录成功"):res.send("用户名密码错误")
    }else{
        res.send("验证码错误")
    }
   
})


router.get("/reg", (req, res) => {
    //res.send("注册")
    res.render("pages/loginAndRegister/register.html")
})

router.post('/reg', (req, res) => {
    let onoff = persons.find(val => val.username == req.body.username)
    if (onoff) {
        res.send("用户名已经被占用")
    } else {
        res.send("注册成功")
        persons.push({
            "username": req.body.username,
            "password": req.body.password
        })
        fs.writeFileSync('D:/Offcn/EP3/day10/xiaou/persons.json', JSON.stringify(persons), { flag: "w" })
    }
})

module.exports = router;